package com.suse.warmstill.config;

import com.alibaba.fastjson.JSONObject;


import com.suse.warmstill.common.Datas;
import com.suse.warmstill.common.handler.CustomerInterceptor;
import com.suse.warmstill.service.ChatMsgService;
import com.suse.warmstill.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.jctools.maps.NonBlockingHashSet;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;

import javax.annotation.Resource;

/**
 * 网络Socket配置
 *
 * @author zed
 * @date 2022/12/09
 */
@Slf4j
@Configuration // 配置类
@EnableWebSocketMessageBroker // 启动WebSocket
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {


    // 配置客户端的连接地址
    // STOMP，Streaming Text Orientated Message Protocol，是流文本定向消息协议，
    // 是一种为MOM(Message Oriented Middleware，面向消息的中间件)设计的简单文本协议。
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 添加客户端连接的url，需要用到SockJS，http://localhost:8080/chat
        registry.addEndpoint("/chat")
                .setAllowedOriginPatterns("*") // 允许跨域访问
                .withSockJS(); // 开启stomp协议
    }

    // 获取所有用户状态：连接，关闭，发送信息，是否被禁言
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        //通过拦截器去实现的
        registration.interceptors(new CustomerInterceptor());
    }

    // 主要用于处理用户断开连接
    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {

        registry.addDecoratorFactory(webSocketHandler ->
                new WebSocketHandlerDecorator(webSocketHandler) {

                    // 用户断开连接，需要将用户从房间中移除
                    @Override
                    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {


                        // 获取sessionId
                        String sessionId = session.getId();

                        final UserInfo remove = Datas.sessionUserInfo.remove(sessionId);

                        if (!ObjectUtils.isEmpty(remove)) {
                            log.info("删除了 session----->{},userInfo------->", session.getId(), remove);
                        }
                    }

                });

    }


}
